<template>
    <div class="container-fluid">
        <div class="row mb-1">
            <div class="col">
                <el-input placeholder="请输入内容" @change="start" v-model.lazy="like">

                </el-input>
            </div>

        </div>
        <div class="row  mb-1">
            <div class="col">
                <el-button @click="start" type="primary">
                    搜索
                </el-button>
                <el-button @click="dialogVisible = true" type="primary">+创建活动签到</el-button>
            </div>
        </div>
        <div class="row  mb-1">
            <div class="col">
                <el-table :data="tableData" border height="65vh" style="width: 100%" @sort-change="sortchange">
                    <el-table-column prop="ID" label="ID" width="80"></el-table-column>
                    <el-table-column prop="name" label="活动名"></el-table-column>
                    <el-table-column prop="starttext" label="签到扫码后文案"></el-table-column>
                    <el-table-column prop="endtext" label="签到成功后文案">
                    </el-table-column>
                    <el-table-column prop="createdAt" width="180"
                        :formatter="(data: any) => { return data.starttime ? formatter(data.starttime) + '-' + formatter(data.endtime ? data.endtime : '') : '' }"
                        label="签到有效期">
                    </el-table-column>
                    <el-table-column label="操作" width="380">
                        <template #default="scope">
                            <router-link :to="{ name: '活动签到首页', params: { ID: scope.row.ID } }" custom
                                v-slot="{ navigate }">
                                <el-button @click="navigate" type="info">查看签到人员</el-button>
                            </router-link>
                            <el-button @click="showimagesss(scope.row)" type="info">二维码</el-button>
                            <el-button @click="handleClick(scope.row)" type="warning">修改</el-button>
                            <el-button type="danger" @click="del(scope.row.ID)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="row  mb-1">
            <div class="col">
                <el-pagination :hide-on-single-page="true" @current-change="handleCurrentChange" :page-size="20"
                    layout="prev, pager, next" :total="count"></el-pagination>
            </div>
        </div>


        <el-dialog :title="title" v-model="dialogVisible" width="80%">
            <el-form size="default" :model="ruleForm" :rules="rules" ref="ruleForms" label-width="200px"
                class="demo-ruleForm" label-position="right">
                <el-form-item label="活动名">
                    <el-input v-model="ruleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="签到扫码后文案">
                    <el-input v-model="ruleForm.starttext"></el-input>
                </el-form-item>
                <el-form-item label="签到成功后文案">
                    <el-input v-model="ruleForm.endtext"></el-input>
                </el-form-item>
                <el-form-item label="签到有效期">
                    <el-date-picker v-model="times"
                        @change="([a, b]: any[]) => { ruleForm.starttime = a; ruleForm.endtime = b }" type="daterange"
                        range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
                </el-form-item>
                <!-- <el-form-item label="当天签到次数限制">
                    <el-input-number v-model="ruleForm.signincount" :min="1" :max="10" :step="1" />
                </el-form-item> -->
                <el-form-item label="可签到人员范围选择">
                    <el-radio-group v-model="ruleForm.isuser">
                        <el-radio :label="false">所有用户</el-radio>
                        <el-radio :label="true">指定人员</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否必须输入一段文字">
                    <el-radio-group v-model="ruleForm.istext">
                        <el-radio :label="false">否</el-radio>
                        <el-radio :label="true">是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否必须上传图片1张">
                    <el-radio-group v-model="ruleForm.isimage">
                        <el-radio :label="false">否</el-radio>
                        <el-radio :label="true">是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="跳转地址">
                    <el-input v-model="ruleForm.url">
                    </el-input>
                </el-form-item>
                <el-form-item label="选择人员" v-if="!ruleForm.ID" v-show="ruleForm.isuser">
                    <el-input placeholder="请输入内容" :model-value="users.map(e => e.name)" readonly
                        class="input-with-select">
                        <template #append>
                            <el-button @click="dialogVisible2 = true">选择用户 </el-button>
                        </template>
                    </el-input>

                    <el-dialog title="请选择用户" v-model="dialogVisible2" width="900px" close-on-click-modal
                        close-on-press-escape>
                        <User :tablekey="['name', 'headportrait']" :handleSelectionChange="handleSelectionChange">
                        </User>
                        <template #footer>
                            <span class="dialog-footer">
                                <el-button @click="dialogVisible2 = false">关闭</el-button>
                            </span>
                        </template>
                    </el-dialog>
                </el-form-item>
                <el-form-item label="选择团队" v-if="!ruleForm.ID" v-show="ruleForm.isuser">
                    <el-select v-model="teams" placeholder="请选择搜索团队" multiple filterable :remote-method="remoteMethod1"
                        remote clearable reserve-keyword>
                        <el-option v-for="item in getteam" :key="item.ID" :label="item.name" :value="Number(item.ID)">
                        </el-option>
                    </el-select>
                </el-form-item>
                <div class="row">
                    <div class="col text-right">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="submit">确 定</el-button>
                    </div>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog title="二维码" v-model="dialogVisible3" width="500px">
            <img :src="imgurl" width="400" ref="imagesss">
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import QRCode from 'qrcode';
import { computed, onMounted, ref, watch } from "vue";
import { useStore } from "vuex";
import User from "../../../admin/views/User/index.vue";
import {
    asynccreatesigninactivity,
    asyncdelsigninactivity,
    asyncselectsigninactivity,
    asyncupdatesigninactivity,
} from "../../../api/index";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import mergeImages from "../../../util/merge-images";
import { toLocaleDateString } from "../../../util/time";

const imagesss = ref()

const times = ref()

const dialogVisible = ref(false)
const count = ref(0)
const tableData = ref<Studycodemodel.Isigninactivity[]>([])
const rules: any[] = []
const dialogVisible2 = ref(false)
const offset = ref(0)
const like = ref('')
const imgurl = ref('')
const dialogVisible3 = ref(false)

function showimagesss(row: Studycodemodel.Isigninactivity) {
    dialogVisible3.value = true
    const test = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc38a242cea953176&redirect_uri=https%3A%2F%2Fwww.hterobot.com%2Fwechat%2Fredirect_uri%2F${row.ID}&response_type=code&scope=snsapi_userinfo&state=5#wechat_redirect`
    setTimeout(() => {
        QRCode.toDataURL(test, {
            type: 'image/png',
            width: 414,
        },
            async (err, url) => {
                const mig = await fetch('https://cdn.hterobot.com/JOY/qiandao.png')
                const n = await mig.blob()
                const fileReader = new FileReader()
                fileReader.readAsDataURL(n)
                fileReader.onloadend = (e) => {
                    var result = e.target?.result as string
                    mergeImages([{ src: result }, { src: url, x: 414, y: 860 }, { src: String(row?.name), format: 'text', fontSize: '80px', color: '#fff', x: 279, y: 400 },], {
                        width: 1243,
                        height: 2208,
                    }).then(e => {
                        imgurl.value = e as string
                    })
                }
            }
        )
    }, 100);
}

const ruleForm = ref<Studycodemodel.Isigninactivity>({

})

async function start() {
    try {
        let z: [keyof Studycodemodel.Inotice, any] | undefined;
        if (like.value) {
            z = ["name", like.value];
        }
        const data = await asyncselectsigninactivity({
            _offset: offset.value,
            _limit: 20,
            _like: z,

        });
        tableData.value = data.rows;
        count.value = data.count;
    } catch (e: any) {
        ElMessage.error(e);
    }
}

function handleCurrentChange(val: number) {
    offset.value = 20 * (val - 1);
}
const title = ref('添加')

function handleClick(row: Studycodemodel.Isigninactivity) {
    title.value = "修改";
    ruleForm.value = row
    if (row.starttime) {
        times.value = [row.starttime, row.endtime]
    }
    dialogVisible.value = true;
}

const oredr = ref('ID')
const sortable = ref('DESC')
function sortchange(row: any) {
    const { prop, order } = row;
    if (order == "descending") {
        sortable.value = "DESC";
    } else {
        sortable.value = "ASC";
    }
    order.value = prop;
}

function formatter(updatedAt: string) {
    return toLocaleDateString(updatedAt);
}

function del(ID: number) {
    try {
        ElMessageBox.confirm("是否删除该选项, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
            .then(async () => {
                await asyncdelsigninactivity({ ID });
                ElMessage({
                    type: "success",
                    message: "删除成功!",
                });
                start();
            })
            .catch((e: string) => {
                ElMessage({
                    message: "删除失败" + e,
                    type: "error",
                });
            });
    } catch (e: any) {
        ElMessage({
            type: "info",
            message: "已取消删除",
        });
    }
}
const loading = ref(false)
const store = useStore(Storekey)
const getteam = computed(() => {
    return store.state.team?.rows || []
})
async function remoteMethod1(query: string | number) {
    if (query !== "") {
        const like: any = ["ID", query];
        if (Number(query) != query) {
            like[0] = "name";
        }
        loading.value = true;
        await store.dispatch("actionteam", {
            _like: like,
        });
        loading.value = false;
    }
}

watch(() => dialogVisible.value, e => {
    if (!e) {
        ruleForm.value = {}
        times.value = []
    }
})

async function submit() {
    try {
        if (ruleForm.value.ID) {
            await asyncupdatesigninactivity(ruleForm.value)
            ElMessage({
                message: "修改成功",
                type: "success",
            });
        } else {
            await asynccreatesigninactivity({
                ...ruleForm.value,
                users: users.value.map(e => e.ID),
                teams: teams.value
            });
            ElMessage({
                message: "添加成功",
                type: "success",
            });
        }
        start();
        dialogVisible.value = false;

    } catch (e: any) {
        ElMessage({
            message: e,
            type: "error",
        });
    }
}
const users = ref<Studycodemodel.Iuser[]>([])
function handleSelectionChange(data: Studycodemodel.Iuser[]) {
    users.value = data
}

const teams = ref<number[]>([])


onMounted(() => {
    start()
})
</script>